/*
 * Copyright (C) 2012-2013 Michael L.R. Marques
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 * 
 * Contact: michaellrmarques@gmail.com
 */

package com.jm.commons.components.panel;

import java.awt.Component;
import java.beans.PropertyEditorSupport;
import java.io.File;
import java.io.IOException;

/**
 * @code{PropertyEditorSupport} for choosing an image
 * 
 * @created Nov 27, 2012
 * @author Michael L.R. Marques
 */
public class ImageEditor extends PropertyEditorSupport {
    
    /**
     * 
     * @return 
     */
    @Override public String getJavaInitializationString() {
        return "";
    }
    
    /**
     * 
     * @param text
     * @throws IllegalArgumentException 
     */
    @Override public void setAsText(String text) throws IllegalArgumentException {
        setValue(text);
    }
    
    /**
     * 
     * @param text
     * @throws IllegalArgumentException 
     */
    @Override public String getAsText() {
        try {
            return (super.getValue() != null) ? ((File) super.getValue()).getCanonicalPath() : "";
        } catch (IOException ioe) {
            System.out.println(ioe.getMessage());
            return ((File) getValue()).getAbsolutePath();
        }
    }
    
    /**
     * 
     * @return 
     */
    @Override public Component getCustomEditor() {
        return new ImageChooser();
    }
    
    /**
     * 
     * @return 
     */
    @Override public boolean supportsCustomEditor() {
        return true;
    }
    
    /**
     * 
     * @param value 
     */
    @Override public void setValue(Object value) {
        if (value instanceof String) {
            if (value != null &&
                    !value.toString().isEmpty() &&
                        !new File(value.toString()).exists()) {
                super.setValue(new File(value.toString()));
            }
        } else if (value instanceof File) {
            super.setValue(value);
        }
    }
    
}
